package com.tieba.service.impl;


import com.tieba.mapper.MessageMapper;
import com.tieba.mapper.UserMapper;
import com.tieba.pojo.*;
import com.tieba.service.MailService;
import com.tieba.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MessageServiceImpl implements MessageService {


    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MailService mailService;

    @Override
    public List<Message> list() {

        return messageMapper.list();
    }

    @Override
    public Message getById(Integer id) {
        return messageMapper.getById(id);
    }

    @Override
    public List<Message> listByOwerId(Integer id) {
        return messageMapper.listByOwerId(id);
    }

    @Override
    public List<Message> listByCommentedId(Integer id) {
        return messageMapper.listByCommentedId(id);
    }

    @Override
    public void add(Message message) {
        message.setLikes(0);
        message.setComments(0);
        message.setCollections(0);
        message.setCreateTime(LocalDateTime.now());
        if(message.getCommentedId() != null){
            Message commentedM = messageMapper.getById(message.getCommentedId());
            commentedM.setComments(commentedM.getComments() + 1);
            messageMapper.update(commentedM);
            User user = userMapper.getById(message.getUserId());
            //如果是管理员发了评论
            if(user.getPermission() == 0){
                log.info("管理员(id={}) 回复了评论(id={})",user.getId(),message.getCommentedId());
                //如果被回复的评论所有者的邮箱不为空，那么就在新增评论的同时发送一封邮件
                User commentedUser = userMapper.getById(commentedM.getUserId());
                if(commentedUser.getEmail() != null) {
                    log.info("管理员向该评论的用户{}的邮箱{}发送了提醒",commentedUser.getId(),commentedUser.getEmail());
                    Mail mail = new Mail();
                    mail.setTo(commentedUser.getEmail());
                    mail.setSubject("管理员回复了你的评论");
                    mail.setText(message.getMessage() + "\n来自你的评论：\n" +commentedM.getMessage());
                    mailService.sendTextMailMessage(mail.getTo(),mail.getSubject(),mail.getText());
                }
                else{
                    log.info("该评论的用户没有设置邮箱！");
                }
            }
        }

        messageMapper.add(message);
    }

    //删除帖子或者评论
    @Override
    public void delete(List<Integer> ids) {

        //Integer id = ids.get(0);
        if(CollectionUtils.isEmpty(ids)){
            return;
        }
        for(Integer id : ids) {
            Message message = messageMapper.getById(id);
            if(message == null){
                return;
            }
            //查找点赞表中点赞了该评论的项,并删除
            List<Integer> likeIds = messageMapper.getIdsByLikeID(id);
            log.info("点赞了该评论的列表:{}",likeIds);
            if(!CollectionUtils.isEmpty(likeIds)){//如果非空
                messageMapper.deleteLike(likeIds);
            }
            //查找收藏表中收藏了该评论的ids，并更新收藏表中对应项的existed为false
            List<Integer> collectionIds = messageMapper.getByCollectionID(id);
            log.info("收藏了该评论的列表:{}",likeIds);
            if(!CollectionUtils.isEmpty(collectionIds)){
                messageMapper.updateCollection(collectionIds);
            }
            //如果是一个帖子
            if(message.getCommentedId() == null){
                //获取评论了这个帖子的所有评论，同样,进行删除(递归)
                List<Integer> messageIds = messageMapper.getBycommentedId(id);
                delete(messageIds);
            }
        }
        messageMapper.delete(ids);
    }

//    @Override
//    public void update(Message message) {
//
//    }


    @Override
    public List<Message> listLike(Integer userId) {
        List<Integer> ids = messageMapper.listLikeByUserId(userId);
        return messageMapper.listByIds(ids);
    }


    @Override
    public List<Message> listComment(Integer userId) {
        List<Integer> ids = messageMapper.listCommentByUserId(userId);
        return messageMapper.listByIds(ids);
    }

    @Override
    public List<Message> listCollection(Integer userId) {
        List<Integer> colllectedMessageIds = messageMapper.listCollectionByUserId(userId);
        //log.info("用户收藏了:{}",colllectedMessageIds);
        if(CollectionUtils.isEmpty(colllectedMessageIds)){
            return null;
        }
        return messageMapper.listByIds(colllectedMessageIds);
    }

    /**
     * 点了一个赞，被点赞的留言likes数加1，同时保存用户和被点赞留言的id，下面的收藏同理
     * @param like
     */
    @Override
    public void addlike(Like like) {
        Message message = messageMapper.getById(like.getMessageId());
        //log.info("原来的点赞:{}",message.getLikes());
        if(message != null) {
            message.setLikes(message.getLikes() + 1);
            //log.info("新的点赞:{}",message.getLikes());
            messageMapper.update(message);
            messageMapper.addlike(like);
        }
    }

    @Override
    public void addcomment(Comment comment) {
        messageMapper.addcomment(comment);
    }

    @Override
    public void addcollection(Collection collection) {
        Message message = messageMapper.getById(collection.getMessageId());
        message.setCollections(message.getCollections() + 1);
        messageMapper.update(message);
        collection.setCreateTime(LocalDateTime.now());
        collection.setExisted(true);
        log.info("收藏时间：{}",collection.getCreateTime());
        messageMapper.addcollection(collection);
    }

//    @Override
//    public Integer getByUserIdAndCommentedId(Integer userId, Integer commentedId) {
//        return messageMapper.getByUserIdAndCommentedId(userId,commentedId);
//    }

    @Override
    public void deleteLike(Like like) {
        Message message = messageMapper.getById(like.getMessageId());
        message.setLikes(message.getLikes() - 1);
        messageMapper.update(message);
        List<Integer> likeIds = List.of(like.getId());
        messageMapper.deleteLike(likeIds);
    }

    @Override
    public void deleteCollection(Collection collection) {
        Message message = messageMapper.getById(collection.getMessageId());
        message.setCollections(message.getCollections() - 1);
        messageMapper.update(message);
        messageMapper.deleteCollection(collection);
    }

    @Override
    public List<Integer> listLikedUsers(Integer messageId) {
        List<Integer> ids = new ArrayList<>();
        for(Like like : messageMapper.getByLikeID(messageId)) {
            ids.add(like.getUserId());
        }
        //去重
        ids = ids.stream().distinct().collect(Collectors.toList());
        return ids;
    }

    @Override
    public List<Integer> listCollectedUsers(Integer messageId) {
        List<Integer> UserIds = messageMapper.getUserIdByCollectionID(messageId);
        //集合去重
        UserIds = UserIds.stream().distinct().collect(Collectors.toList());
        return UserIds;
    }
}
